package com.blog.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.blog.domain.Post;
import com.blog.domain.Post_;

@Repository("postDao")
public class PostDao {
    @Autowired
    private SessionFactory sessionFactory;

    public List<Post> getTop10Posts() {
        EntityManager etm = sessionFactory.getCurrentSession().getEntityManagerFactory().createEntityManager();
        List<Post> top10 = etm.createNamedQuery("getTop10Post",Post.class).setMaxResults(10).getResultList();
        return top10;
    }

    public Post findPost() {
        EntityManager etm = sessionFactory.getCurrentSession().getEntityManagerFactory().createEntityManager();
        return etm.find(Post.class, 2L);
    }

    /**
     * For generating jpa_metamodel by eclipse, please refer to screenshots under eclipse_generate_jpa_meta_model folder.
     * @param id
     * @return
     */
    public Post findPostById(long id) {
        EntityManager entityManager = sessionFactory.getCurrentSession().getEntityManagerFactory().createEntityManager();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();

        CriteriaQuery<Post> criteria = builder.createQuery(Post.class);
        Root<Post> root = criteria.from(Post.class);
        criteria.select(root);
        criteria.where(builder.equal(root.get(Post_.id), id));

        return entityManager.createQuery(criteria).getResultList().get(0);
    }
}
